package com.ilancuo.datastructuresandalgorithmsinjava.ch04_stack_list;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * 单词逆序
 * Created by ilancuo on 2018/8/19.
 */
class StackY {
    private int maxSize;
    private char[] stackArray;
    private int top;

    public StackY(int max) {
        maxSize = max;
        stackArray = new char[max];
        top = -1;
    }

    public void push(char j) {
        stackArray[++top] = j;
    }

    public char pop() {
        return stackArray[top--];
    }

    public char peek() {
        return stackArray[top];
    }

    public boolean isEmpty() {
        return (top == -1);
    }

}

class Reverser {
    private String input;
    private String output;

    public Reverser(String input) {
        this.input = input;
    }

    public String doReverse() {
        int stackSize = input.length();
        StackY theStack = new StackY(stackSize);
        for (int j = 0; j < stackSize; j++) {
            char ch = input.charAt(j);
            theStack.push(ch);
        }
        output = "";
        while (!theStack.isEmpty()) {
            char ch = theStack.pop();
            output = output + ch;
        }
        return output;
    }
}

public class Reverse {
    public static void main(String[] args) throws IOException {
        String input, output;
        while (true) {
            System.out.println("Enter a string:");
            input = getStr();
            if (input.equals("")) break;
            Reverser theReverser = new Reverser(input);
            output = theReverser.doReverse();
            System.out.println("Reversed: " + output);
        }
    }

    /**
     * 老版本的写法
     */
    public static String getString() throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String s = br.readLine();
        return s;
    }

    public static String getStr() {
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }
}
